package com.pai4j.common.util.community;


import lombok.Data;
import lombok.extern.slf4j.Slf4j;

import java.util.concurrent.CountDownLatch;
import java.util.concurrent.Executor;

/**
 *  多任务并行批处理工具
 *
 * @author: CYM-pai
 * @date: 2025/10/28 20:55
 **/
@Slf4j
@Data
public class BatchHandleExecutor {

    private CountDownLatch latch;

    private Executor executor;

    /***
     * 构造一个批处理工具
     * @param size 任务数
     * @param executor 线程池由业务指定
     * @return
     */
    public static BatchHandleExecutor init(int size, Executor executor) {
        BatchHandleExecutor batchHandleExecutor = new BatchHandleExecutor();
        CountDownLatch latch = new CountDownLatch(size);
        batchHandleExecutor.setLatch(latch);
        batchHandleExecutor.setExecutor(executor);
        return batchHandleExecutor;
    }

    public void execute(Runnable task) {
        executor.execute(() -> {
            try {
                task.run();
            } catch (Exception e) {
                log.error("BatchHandleExecutor.execute error.", e);
            } finally {
                latch.countDown();
            }
        });
    }

    public void await() {
        try {
            latch.await();
        } catch (Exception e) {
            log.error("BatchHandleExecutor.await error.", e);
        }
    }

}
